#!/bin/bash

# =======================================================
# 脚本名称: extractor.sh
# 脚本功能: 通用解压缩脚本，自动识别压缩文件类型并解压。
# 支持格式: tar.bz2, tar.gz, tar.xz, bz2, rar, gz,
#           tar, tbz2, tgz, zip, Z, 7z, xz, lzma,
#           arj, cab, deb, rpm, cpio, iso, ace, shar, uue, lha, lzh.
# 使用方法: ./extractor.sh <压缩文件路径>
# 依赖工具: tar, bzip2, rar, gzip, unzip, ncompress, p7zip-full,
#           xz-utils, arj, cabextract, dpkg, rpm, cpio, genisoimage,
#           unace, unrar, sharutils, uudeview, mpack, file-roller。
# 仅支持系统: Debian/Ubuntu
# =======================================================

# 检查操作系统是否为 Debian/Ubuntu
if ! grep -Ei 'debian|ubuntu' /etc/os-release &> /dev/null; then
    echo "错误：此脚本仅支持 Debian/Ubuntu 系统。"
    exit 1
fi

# 检查所需软件包是否安装
check_and_install() {
    local missing_pkgs=()
    for pkg in tar bzip2 rar gzip unzip ncompress p7zip-full p7zip-rar xz-utils arj cabextract dpkg rpm cpio genisoimage \
               unace unrar zip sharutils uudeview mpack file-roller; do
        if ! dpkg -s "$pkg" &> /dev/null; then
            missing_pkgs+=("$pkg")
        fi
    done
    if [ ${#missing_pkgs[@]} -gt 0 ]; then
        echo "缺少以下依赖软件包: ${missing_pkgs[*]}，正在安装..."
        sudo apt-get update
        sudo apt-get install -y "${missing_pkgs[@]}"
    fi
}

# 调用依赖检查函数
check_and_install

# 函数名称: extract
# 功能描述: 根据文件扩展名自动解压缩文件
extract() {
    if [ -f "$1" ]; then
        case "$1" in
            *.tar.bz2)   tar xvjf "$1"    ;;
            *.tar.gz)    tar xvzf "$1"    ;;
            *.tar.xz)    tar Jxvf "$1"    ;;
            *.bz2)       bunzip2 "$1"     ;;
            *.rar)       unrar x "$1"     ;;
            *.gz)        gunzip "$1"      ;;
            *.tar)       tar xvf "$1"     ;;
            *.tbz2)      tar xvjf "$1"    ;;
            *.tgz)       tar xvzf "$1"    ;;
            *.zip)       unzip -d "$(basename "$1" .zip)" "$1" ;;
            *.Z)         uncompress "$1"  ;;
            *.7z)        7z x "$1"        ;;
            *.xz)        xz -d "$1"       ;;
            *.lzma)      lzma -d "$1"     ;;
            *.arj)       arj x "$1"       ;;
            *.cab)       cabextract "$1"  ;;
            *.deb)       dpkg -x "$1" "${1%.deb}" ;;
            *.rpm)       rpm2cpio "$1" | cpio -idmv ;;
            *.cpio)      cpio -idmv < "$1" ;;
            *.iso)       isoinfo -i "$1" -x / | tar xv  ;;
            *.ace)       unace x "$1"     ;;
            *.shar)      unshar "$1"      ;;
            *.uue)       uudecode "$1"    ;;
            *.lha|*.lzh) lha x "$1"       ;;
            *.mpack)     mpack -d "$1"    ;;
            *)
                echo "无法解压文件 '$1'：不支持的格式"
                ;;
        esac
    else
        echo "错误：'$1' 不是有效的文件！"
    fi
}

# 主程序入口
main() {
    if [ $# -eq 0 ]; then
        echo "用法: $0 <压缩文件路径>"
        exit 1
    fi
    extract "$1"
}

# 执行主程序
main "$@"
